package com.kaoshi.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kaoshi.common.config.Result;
import com.kaoshi.user.config.UsernameHolder;
import com.kaoshi.user.pojo.Enter;
import com.kaoshi.user.mapper.EnterMapper;
import com.kaoshi.user.service.EnterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-29
 */
@Service
public class EnterServiceImpl extends ServiceImpl<EnterMapper, Enter> implements EnterService {
    @Resource
    private EnterMapper enterMapper;

    @Override
//    public Result login(Enter enter) {
//        LambdaQueryWrapper<Enter> qr = new LambdaQueryWrapper<>();
//        qr.eq(Enter::getUsername, enter.getUsername());
//        Enter one = enterMapper.selectOne(qr);
//        if (one == null) {
//            return Result.fail("用户名错误");
//        }
//        if (!one.getPassword().equals(enter.getPassword())) {
//            return Result.fail("密码错误");
//        }
//        return Result.ok(one);
//    }

    // 登录方法
    public Result login(Enter enter) {
        LambdaQueryWrapper<Enter> qr = new LambdaQueryWrapper<>();
        qr.eq(Enter::getUsername, enter.getUsername());
        Enter one = enterMapper.selectOne(qr);

        if (one == null) {
            return Result.fail("用户名错误");
        }

        // 使用 BCrypt 密码编码器验证密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(enter.getPassword(), one.getPassword())) {
            return Result.fail("密码错误");
        }

        UsernameHolder.setUsername(enter.getUsername());

        return Result.ok(one);
    }
}
